package com.kestrel.space.core.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.kestrel.space.common.constants.COSConstants;
import com.kestrel.space.common.model.User;
import com.kestrel.space.common.utils.Generator;
import com.kestrel.space.common.utils.LargePage;
import com.kestrel.space.core.mapper.FileMapper;
import com.kestrel.space.core.model.FileMappingOrg;
import com.kestrel.space.core.model.FileMappingUser;
import com.kestrel.space.core.model.MyFile;
import com.kestrel.space.core.query.MyFileQuery;
import com.kestrel.space.core.service.CosService;
import com.kestrel.space.core.service.FileMappingOrgService;
import com.kestrel.space.core.service.FileMappingUserService;
import com.kestrel.space.core.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;


/**
 * @Author: kestrel
 * @Version:1.0
 * @Date: 2024/8/21
 */
@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private CosService cosService;

    @Autowired
    private FileMapper fileMapper;

    @Autowired
    private FileMappingOrgService fileMappingOrgService;

    @Autowired
    private FileMappingUserService fileMappingUserService;

    @Override
    public List<MyFile> listContent(MyFileQuery query, LargePage page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNum(), page.getPageSize());
        }
        MyFile file = BeanUtil.copyProperties(query, MyFile.class);
        return fileMapper.select(file);
    }

    @Override
    public String saveOrUpdate(MyFile file) {
        String message = "插入成功";
        if (file.getId() == null) {
            file.setId(Generator.generateId());
            fileMapper.insert(file);
        } else {
            message = "更新成功";
            fileMapper.updateByPrimaryKeySelective(file);
        }
        return message;
    }

    @Override
    public String batchSaveOrUpdate(List<MyFile> fileList) {
        String message = "批量插入成功";
        if (CollectionUtils.isEmpty(fileList)) {
            return "集合为空";
        }
        if(fileList.get(0).getId() == null){
            for (MyFile file : fileList) {
                file.setId(Generator.generateId());
                fileMapper.insert(file);
            }
        } else {
            message = "批量更新成功";
            for (MyFile file : fileList) {
                file.setId(Generator.generateId());
                fileMapper.updateByPrimaryKey(file);
            }
        }
        return message;
    }

    @Override
    public String uploadFile(MultipartFile file, String type, String osUrl, User user, String md5) {
        Long fileId;
        // 秒传逻辑实现
        MyFile check = new MyFile();
        check.setMd5(md5);
        List<MyFile> fileList = fileMapper.selectByExample(check);
        if(fileList == null || fileList.isEmpty()){
            String cosUrl = cosService.upload(file, type, user);
            MyFile myFile = new MyFile(Generator.generateId(),file.getOriginalFilename(),type,false,0,cosUrl,osUrl,new Date(),new Date(), md5);
            fileMapper.insert(myFile);
            fileId = myFile.getId();
        } else {
            fileId = fileList.get(0).getId();
        }

        FileMappingUser fileMappingUser = new FileMappingUser();
        fileMappingUser.setFileId(fileId);
        fileMappingUser.setUserId(user.getId());
        fileMappingUser.setCreateTime(new Date());
        fileMappingUser.setUpdateTime(new Date());
        fileMappingUserService.saveOrUpdate(fileMappingUser);
        return "上传文件成功";
    }

    @Override
    public String deleteFile(Long id) {
        MyFile myFile = new MyFile();
        myFile.setId(id);
        myFile.setIfDeleted(true);
        myFile.setUpdateTime(new Date());
        Example example = new Example(MyFile.class);
        example.createCriteria().andEqualTo("id",id);
        fileMapper.updateByExample(myFile,example);
        return "删除文件成功";
    }

    @Override
    public String synchronizationFile(Long id, User user) {
        String fileUrl = fileMapper.selectByPrimaryKey(id).getFileCosUrl();
        List<MyFile> fileList = cosService.synchronization(fileUrl, user);
        batchSaveOrUpdate(fileList);
        return "文件至博客系统成功";
    }

    @Override
    public String downloadFile(Long id, HttpServletRequest request, HttpServletResponse response) {
        String fileUrl = fileMapper.selectByPrimaryKey(id).getFileCosUrl();
        cosService.download(fileUrl, request, response);
        return "下载成功";
    }

    @Override
    public MyFile selectFileById(Long id) {
        return fileMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<MyFile> listOrganizationFiles(MyFileQuery query) {
        query.setMark(0);
        return fileMapper.listOrganizationFiles(query);
    }

    @Override
    public String allocate(Long fileId, Long organizationId, boolean stage) {
        FileMappingOrg fileMappingOrg = new FileMappingOrg();
        fileMappingOrg.setFileId(fileId);
        fileMappingOrg.setOrganizationId(organizationId);
        fileMappingOrg.setIfDeleted(stage);
        return fileMappingOrgService.saveOrUpdate(fileMappingOrg);
    }

    @Override
    public List<Long> listMyFilesInOrg(User user, Long organizationId) {
        return fileMapper.listMyFilesInOrg(user.getId(), organizationId);
    }

    @Override
    public String previewFile(Long id) {
        String downloadUrl = COSConstants.PATH;
        downloadUrl += ((MyFile) fileMapper.selectByExample(id)).getFileCosUrl();
        return downloadUrl;
    }
}
